import request from '../utils/request';
import { ApiResponse, Request, PageResult } from '../types';

/**
 * 获取求种列表
 */
export const getRequests = (params: any): Promise<ApiResponse<PageResult<Request>>> => {
  return request<ApiResponse<PageResult<Request>>>({
    url: '/requests',
    method: 'get',
    params
  });
};

/**
 * 获取求种详情
 */
export const getRequestDetail = (id: number): Promise<ApiResponse<Request>> => {
  return request<ApiResponse<Request>>({
    url: `/requests/${id}`,
    method: 'get'
  });
};

/**
 * 发布求种
 */
export const createRequest = (data: any): Promise<ApiResponse<Request>> => {
  return request<ApiResponse<Request>>({
    url: '/requests',
    method: 'post',
    data
  });
};

/**
 * 完成求种
 */
export const fillRequest = (requestId: number, torrentId: number): Promise<ApiResponse<null>> => {
  return request<ApiResponse<null>>({
    url: `/requests/${requestId}/fill`,
    method: 'put',
    data: { torrentId }
  });
};

/**
 * 关闭求种
 */
export const closeRequest = (requestId: number): Promise<ApiResponse<null>> => {
  return request<ApiResponse<null>>({
    url: `/requests/${requestId}/close`,
    method: 'put'
  });
};

export const downloadTorrent = async (requestId: number) => {
  const response = await fetch(`/api/requests/${requestId}/download`, {
    credentials: 'include' // 包含认证信息
  });
  
  if (!response.ok) {
    throw new Error('下载失败');
  }
  
  // 获取文件名
  const contentDisposition = response.headers.get('content-disposition');
  let filename = 'unknown.torrent';
  if (contentDisposition) {
    const matches = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(contentDisposition);
    if (matches != null && matches[1]) {
      filename = decodeURIComponent(matches[1].replace(/['"]/g, ''));
    }
  }
  
  // 下载文件
  const blob = await response.blob();
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  window.URL.revokeObjectURL(url);
  document.body.removeChild(a);
}; 